<template>
  <div class="table-box">
    <ProTable ref="proTableRef" row-key="id" title="账户列表" :columns="columns" :request-api="loadTable" highlight-current-row>
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <ElButton type="primary" :icon="CirclePlus" @click="onAddClicked">新增</ElButton>
        <!-- <ElButton type="primary" plain :icon="Upload" @click="onImportClicked">导入</ElButton> -->
        <!-- <ElButton type="primary" plain :icon="Download" @click="onExportClicked">导出</ElButton> -->
      </template>
      <!-- 账户操作 -->
      <template #operation="scope">
        <ElButton type="primary" link :icon="View" @click="onViewClicked(scope.row)">查看</ElButton>
        <ElButton type="primary" link :icon="EditPen" @click="onEditClicked(scope.row)">编辑</ElButton>
        <ElButton type="primary" link :icon="Delete" @click="onDeleteClicked(scope.row)">删除</ElButton>
      </template>
    </ProTable>
    <AccountForm ref="formRef" @success="refresh" />
    <!-- <UploadPanel ref="uploadFormRef" /> -->
  </div>
</template>

<script setup lang="ts" name="ZLAccount">
import { CirclePlus, Delete, EditPen, View } from '@element-plus/icons-vue'
import AccountForm from './account-form.vue'
import ProTable from '@/components/ProTable/index.vue'
import { ColumnProps, ProTableInstance } from '@/components/ProTable/interface'
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { removeUser, pageUser } from '@api/uc/user'
import { listRoleOption } from '@api/uc/role'
import { getAllDeptTree } from '@/utils/param'
import { User } from '@api/uc/user/interface'
import { listDictByType } from '@api/uc/dict'
import { FormType } from '@/enums'
const proTableRef = ref<ProTableInstance>()

// const uploadFormRef = ref()
// const tableData = []

function refresh() {
  proTableRef.value?.getTableList()
}

// 用户状态字典
// async function lockFlagDict() {
//   const data = await listDictByType('status_type')
//   data.data = data.data.map(item => {
//     return {
//       label: item.label,
//       value: item.value,
//       tagType: item.value === '0' ? 'success' : 'danger'
//     }
//   })
//   return data
// }

// 用户类别
async function userTypes() {
  const data = await listDictByType('user_type')
  return data
}
// 部门树
async function treeDept() {
  const data = await getAllDeptTree()
  return { data }
}

// 部门树
function roleOptions() {
  return listRoleOption()
}

function getIndex(index: number) {
  const { current, size } = proTableRef.value!.pageable
  return (current - 1) * size + index + 1
}

// 表格列
const columns = reactive<ColumnProps<User.Record>[]>([
  // { type: 'avatar', label: '头像', width: 60 },
  { type: 'index', label: '序号', width: 60, index: getIndex },
  { prop: 'username', label: '用户名', search: { el: 'input', key: 'username', order: 3 }, align: 'center', minWidth: 150 },
  { prop: 'nickname', label: '昵称', search: { el: 'input', key: 'nickname' }, align: 'center', minWidth: 150 },
  {
    prop: 'deptId',
    label: '部门',
    enum: treeDept,
    search: { el: 'tree-select', key: 'deptId', order: 2, props: { checkStrictly: true } },
    fieldNames: { label: 'name', value: 'id' },
    minWidth: 150
  },
  { prop: 'phone', label: '手机号', align: 'center', search: { el: 'input', key: 'phone', order: 4 }, minWidth: 120 },
  { prop: 'email', label: '邮箱', align: 'center', minWidth: 180, isShow: false },
  { prop: 'roleId', label: '角色', align: 'center', enum: roleOptions, search: { el: 'select', key: 'roleId' } },
  { prop: 'type', label: '用户类别', align: 'center', enum: userTypes, search: { el: 'select', key: 'type' } },
  { prop: 'areaId', label: '区域', search: { el: 'input', key: 'areaId', order: 1 }, isShow: false },
  { prop: 'groupId', label: '分组', search: { el: 'input', key: 'groupId' }, isShow: false },
  { prop: 'postId', label: '岗位', isShow: false },
  // { prop: 'createTime', label: '创建时间', render: scope => dateTimeFormat(scope.row.createTime), isShow: false },
  // { prop: 'updateTime', label: '修改时间', render: scope => dateTimeFormat(scope.row.createTime), isShow: false },
  // { prop: 'lockFlag', label: '状态', enum: lockFlagDict, tag: true, search: { el: 'select' }, width: 100 },
  { prop: 'operation', label: '操作', fixed: 'right', width: 230 }
])

// const excelField = {
//   index: '序号',
//   username: '用户名',
//   nickname: '昵称',
//   phone: '手机号',
//   email: '邮箱',
//   area: '区域',
//   role: '角色',
//   dept: '部门',
//   post: '岗位',
//   sts: '删除状态',
//   lockFlag: '锁定状态',
//   createTime: '创建时间'
// }

const loadTable = (query: User.Query) => {
  query.order = 'update_time desc'
  return pageUser(query)
}
// 打开 drawer(新增、查看、编辑)
const formRef = ref<InstanceType<typeof AccountForm> | null>(null)

// 查看用户
const onViewClicked = (row: any) => {
  formRef.value?.open(FormType.VIEW, row.id)
}

// 添加用户按钮
const onAddClicked = () => {
  formRef.value?.open(FormType.ADD)
}

// 编辑账户
const onEditClicked = (row: any) => {
  formRef.value?.open(FormType.EDIT, row.id)
}

// 删除账户
const onDeleteClicked = (row: any) => {
  ElMessageBox.confirm('您确定要删除该账户吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      removeUser(row.id).then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功!'
        })
        proTableRef.value?.getTableList()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'warning',
        message: '删除取消!'
      })
    })
}

// interface DataItem {
//   [key: string]: any
// }

// interface MappedDataItem extends DataItem {
//   username: string
//   nickname: string
//   phone: string
//   email: string
//   role: string
//   area: string
//   post: string
//   sts: string
//   lockFlag: string
//   dept: string
// }

// const mapToEnglishKeys: Record<string, keyof MappedDataItem> = {
//   用户名: 'username',
//   昵称: 'nickname',
//   手机号: 'phone',
//   邮箱: 'email',
//   角色: 'role',
//   区域: 'area',
//   岗位: 'post',
//   删除状态: 'sts',
//   锁定状态: 'lockFlag',
//   部门: 'dept'
// }

// 从 Excel 表格导入用户
// const onImportClicked = async () => {

//   try {
//     const win: any = window
//     const fileHandle = await win?.showOpenFilePicker({
//       excludeAcceptAllOption: false,
//       types: [
//         {
//           description: 'Excel 工作簿',
//           accept: {
//             'application/vnd.ms-excel': ['.xlsx']
//           }
//         }
//       ]
//     })
//     const file = await fileHandle[0].getFile()
//     const reader = new FileReader()
//     reader.readAsArrayBuffer(file)
//     reader.onload = (e: any) => {
//       let data = e.target.result
//       const workbook = XLSX.read(data, { type: 'binary', cellDates: true })
//       const sheet = workbook.SheetNames[0]
//       const payload: DataItem[] = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
//       const mapFieldToEnglish = (data: DataItem[]): MappedDataItem[] => {
//         return data.map(item => {
//           const mappedItem: MappedDataItem = { ...item } as MappedDataItem

//           Object.keys(item).forEach(key => {
//             const mappedKey = mapToEnglishKeys[key]
//             if (mappedKey) {
//               if (mappedKey == 'sts') {
//                 mappedItem[mappedKey] = mappedItem[key] == '已删除' ? '1' : '0'
//               } else if (mappedKey == 'lockFlag') {
//                 mappedItem[mappedKey] = mappedItem[key] == '已锁定' ? '1' : '0'
//               } else {
//                 mappedItem[mappedKey] = mappedItem[key]
//               }
//               delete mappedItem[key]
//             }
//           })
//           return mappedItem
//         })
//       }

//       const res = mapFieldToEnglish(payload)
//       console.log(res)
//     }
//   } catch (e) {}
// }

// interface Item {
//   username: string
//   nickname: string
//   phone: string
//   email: string
//   area: string
//   role: string
//   dept: string
//   post: string
//   lockFlag: string
//   sts: string
//   createTime: string
// }

// const onExportClicked = () => {
//   // Map raw data to Chinese field names
//   const mappedData = proTableRef.value?.tableData.map((item: Item, index: number) => ({
//     [excelField.index]: index + 1,
//     [excelField.username]: item.username,
//     [excelField.nickname]: item.nickname,
//     [excelField.phone]: item.phone,
//     [excelField.email]: item.email,
//     [excelField.area]: item.area,
//     [excelField.role]: item.role,
//     [excelField.dept]: item.dept,
//     [excelField.post]: item.post,
//     [excelField.sts]: item.sts === '1' ? '已删除' : '未删除',
//     [excelField.lockFlag]: item.lockFlag === '1' ? '已锁定' : '未锁定',
//     [excelField.createTime]: item.createTime
//   }))

//   // 创建工作表
//   const data = XLSX.utils.json_to_sheet(mappedData as any)
//   // 创建工作簿
//   const wb = XLSX.utils.book_new()
//   XLSX.utils.book_append_sheet(wb, data, '账户列表') // 设置工作簿名称
//   // 将工作表放入工作簿中
//   XLSX.utils.book_append_sheet(wb, data, 'data')
//   // 生成文件并下载
//   XLSX.writeFile(wb, '账户.xlsx')
// }
</script>
